package org.bonorsoft.modules.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.bonorsoft.common.api.vo.Result;
import org.bonorsoft.common.aspect.annotation.AutoLog;
import org.bonorsoft.common.system.base.controller.BonorController;
import org.bonorsoft.common.system.query.QueryGenerator;
import org.bonorsoft.modules.control.entity.Unit;
import org.bonorsoft.modules.control.entity.UnitDisplay;
import org.bonorsoft.modules.control.service.IUnitService;
import org.bonorsoft.modules.control.util.MessageUtils;
import org.bonorsoft.modules.system.entity.SysMessages;
import org.bonorsoft.modules.system.service.ISysMessagesService;
import org.bonorsoft.modules.system.service.WsService;
import org.bonorsoft.modules.system.vo.Sign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Date;

/**
 * @Description: 信息通知
 * @Author: WilliamYe
 * @Date: 2021-02-24
 * @Version: V1.0
 */
@Slf4j
@Controller
@RequestMapping("/system/message")
public class SysMessagesController extends BonorController<SysMessages, ISysMessagesService> {
    private String prefix = "system/messages";

    @Autowired
    private ISysMessagesService sysMessagesService;

    @Autowired
    private IUnitService unitService;

    @Autowired
    private WsService wsService;

    /**
     * 首页
     */
    //@RequiresPermissions("system:message:view")
    @GetMapping()
    public String index() {
        return prefix + "/message";
    }

    /**
     * 获取信息条数
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/nums")
    public Result<?> msgNums() {

        int count = sysMessagesService.count(new QueryWrapper<SysMessages>()
                .eq("to_user_id", getLoginUserId())
                .eq("read_status", "0")
        );
        return Result.ok(count);
    }

    @RequestMapping("/announce/{dzbm}")
    public String announce(@PathVariable("dzbm") String dzbm, ModelMap map) {
        map.put("dzbm", dzbm);
        return prefix + "/announce";
    }

    @RequestMapping("/user")
    public String user() {
        return prefix + "/user/user";
    }

    //检查签字
    @GetMapping("/sign/{id}")
    public String sign(@PathVariable("id") String id, ModelMap map) {
        map.put("id", id);
        return prefix + "/sign";
    }

    //检查签字
    @PostMapping(value = "/sign")
    @ResponseBody
    public Result<?> sign(@Validated Sign sign) {
        sysMessagesService.saveSign(sign);
        return Result.ok("添加成功！");
    }

    /**
     * 隐患通知下发
     *
     * @param messages
     * @return
     */
    @ResponseBody
    @RequestMapping("/sendAnnounce")
    public Result<?> sendAnnounce(SysMessages messages) {
        //消息保存
        messages.setFromUserId(getLoginUserId()).setSender(getLoginUserName()).setCreateBy(getLoginUserName()).setCreateTime(new Date());
        sysMessagesService.save(messages);
        int unitCount = unitService.count(new QueryWrapper<Unit>().eq("dwdz_dzbm", messages.getDzbm()));
        if (unitCount > 0) {
            Unit unit = unitService.getOne(new QueryWrapper<Unit>().eq("dwdz_dzbm", messages.getDzbm()));
            //对接短信接口发送
            String tpl_value = URLEncoder.encode("#enterprise#=" + unit.getDwmc() + "&#dangerTitle#=" + messages.getTitle());
            MessageUtils.SendMessage(unit.getLxdh(), tpl_value);
        }
        //发送消息通知
        wsService.sendMessCountToUser(messages.getToUserId());
        return Result.ok("下发成功");
    }

    @RequestMapping("/detail/{id}")
    public String detail(@PathVariable("id") String id, ModelMap map) {
        //消息设置为已读
        sysMessagesService.update(new SysMessages().setReadStatus("1"),
                new UpdateWrapper<SysMessages>().eq("id", id));
        map.put("detail", sysMessagesService.getById(id));
        return prefix + "/detail";
    }

    /**
     * 分页列表查询
     *
     * @param sysMessages
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "信息通知-分页列表查询")
    //@RequiresPermissions("system:message:list")
    @GetMapping(value = "/list")
    @ResponseBody
    public Result<?> queryPageList(SysMessages sysMessages,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<SysMessages> queryWrapper = QueryGenerator.initQueryWrapper(sysMessages, req.getParameterMap());
        queryWrapper.eq("to_user_id", getLoginUserId());
        Page<SysMessages> page = new Page<SysMessages>(pageNo, pageSize);
        IPage<SysMessages> pageList = sysMessagesService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加页面
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 添加
     *
     * @param sysMessages
     * @return
     */
    @AutoLog(value = "信息通知-添加")
    @RequiresPermissions("system:message:add")
    @PostMapping(value = "/add")
    @ResponseBody
    public Result<?> add(@Validated SysMessages sysMessages) {
        sysMessagesService.save(sysMessages);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑页面
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap map) {
        map.put("editInfo", sysMessagesService.getById(id));
        return prefix + "/edit";
    }

    /**
     * 编辑
     *
     * @param sysMessages
     * @return
     */
    @AutoLog(value = "信息通知-编辑")
    @RequiresPermissions("system:message:edit")
    @PostMapping(value = "/edit")
    @ResponseBody
    public Result<?> edit(@Validated SysMessages sysMessages) {
        sysMessagesService.updateById(sysMessages);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "信息通知-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        sysMessagesService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "信息通知-批量删除")
    @RequiresPermissions("system:message:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    @ResponseBody
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.sysMessagesService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "信息通知-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        SysMessages sysMessages = sysMessagesService.getById(id);
        return Result.ok(sysMessages);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param sysMessages
     */
    @AutoLog(value = "信息通知-导出excel")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, SysMessages sysMessages) {
        return super.exportXls(request, sysMessages, SysMessages.class, "信息通知");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @AutoLog(value = "信息通知-通过excel导入数据")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    @ResponseBody
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, SysMessages.class);
    }

    /**
     * 模板下载
     *
     * @return
     */
    @AutoLog(value = "信息通知-模板下载", operateType = 6)
    @RequestMapping(value = "/importTemplate")
    public ModelAndView importTemplate() {
        return super.importTemplateXls(SysMessages.class, "信息通知");
    }

}
